package vn.com.mybudget;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import vn.com.mybudget.base.BaseRouter;
import vn.com.mybudget.base.HTMLView;
import vn.com.mybudget.base.ViewBase;
import vn.com.mybudget.base.XMLView;
import vn.com.mybudget.bo.AccountBO;
import vn.com.mybudget.common.CommonUtil;


@SuppressWarnings("serial")
public class MybudgetServlet extends BaseRouter {
	public ViewBase login() throws IOException{
		if (_currentUser == null){
//	        try {
//	        	//return new HTMLView("login",this);
//				currentRequest.getRequestDispatcher(_userService.createLoginURL(currentRequest.getRequestURI())).forward(currentRequest, currentResponse);
//			} catch (ServletException e) {
//				currentResponse.sendRedirect("/"+_userService.createLoginURL(currentRequest.getRequestURI()));
//			}
			currentResponse.sendRedirect(_userService.createLoginURL("/mybudget?action=index"));
		}
		else{
		    currentResponse.sendRedirect("/");
		}
		return null;
	}
	
	public ViewBase logout() throws IOException{
	        try {
	        	currentRequest.getSession().removeAttribute("email");
	        	_currentAccount = null;
	        	_currentUser = null;
	        	//return new HTMLView("login",this);
				currentRequest.getRequestDispatcher(_userService.createLoginURL(currentRequest.getRequestURI())).forward(currentRequest, currentResponse);
			} catch (ServletException e) {
				currentResponse.sendRedirect("/"+_userService.createLoginURL(currentRequest.getRequestURI()));
			}
		return null;
	}
	
	public ViewBase index() throws IOException{
	    return new HTMLView("index.jsp", this);
	}
	
	public ViewBase welcome() throws IOException{
	    return new HTMLView("welcome.jsp", this);
	}
	
	public ViewBase common() throws IOException{
	    return new HTMLView("common.jsp", this);
	}
	
	public String GetLoginUrl(){
		UserService userService = UserServiceFactory.getUserService();
		return userService.createLoginURL(currentRequest.getRequestURI());
	}
	
	public String loadxslfile(String fileName){
		String content="";
		InputStream inp = this.getServletContext().getResourceAsStream("/WEB-INF/xsl/"+fileName+".xsl");
		try {
			content = CommonUtil.GetXSLFile(inp);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			content = e.getMessage();
		}
		return content;
	}
}
